package com.deer.wms.ASN.manage.web;

import com.deer.wms.ASN.manage.model.file.FileData;
import com.deer.wms.ASN.manage.model.in.AcceptRecord;
import com.deer.wms.ASN.manage.model.in.AcceptRecordCriteria;
import com.deer.wms.ASN.manage.model.qc.*;
import com.deer.wms.ASN.manage.service.AcceptRecordService;
import com.deer.wms.ASN.manage.service.AsnMasterService;
import com.deer.wms.ASN.manage.service.QcRecordService;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
*
 * @author guo
 * @since 2020/01/15
 */
@Api(description = "质检记录api接口")
@RestController
@RequestMapping("/qc/records")
public class QcRecordController {

    @Autowired
    private QcRecordService qcRecordService;
    @Autowired
    private AcceptRecordService acceptRecordService;
    @Autowired
    private AsnMasterService asnMasterService;

    @PostMapping("/insert")
    public Result add(@RequestBody QcRecord qcRecord) {
        qcRecordService.save(qcRecord);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        qcRecordService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody QcRecord qcRecord) {
        qcRecordService.updateById(qcRecord);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        QcRecord qcRecord = qcRecordService.getById(id);
        return ResultGenerator.genSuccessResult(qcRecord);
    }

    @GetMapping("/list")
    public Result list(QcRecordCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<QcRecordDto> list = qcRecordService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    // 质检任务池的进行质检结果确认
    @GetMapping("result")
//    @Transactional
    public Result qcResult(QcResultCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        qcRecordService.qcResult(criteria,currentUser);
        //回传erp
        AcceptRecord acceptRecord = acceptRecordService.getOneByField("accept_record_code", criteria.getBillCode());
//        String billNo = acceptRecord.getAsnBillNo();
//        QcRecord qcRecord = qcRecordService.getOneByField("accept_record_code", criteria.getBillCode());
        String billId = acceptRecordService.billToErpNew(acceptRecord.getAsnBillNo(), criteria.getBillCode());
        //erp审核回传
        if(billId != null){
            acceptRecordService.checkBillToErp(billId);
        }else{
            try {
                throw new Exception("质检回传erp报错");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultGenerator.genSuccessResult();
    }

    // 批量质检提交
    @PostMapping("/submit")
//    @Transactional
    public Result submit(@RequestBody QcResultCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        if(criteria.getQcRecordList()!=null){
//            List<QcRecord> qcRecordList = criteria.getQcRecordList();
//            for (QcRecord qcRecord : qcRecordList) {
//                qcRecord.setQcUserName(currentUser.getUserName());
//                qcRecord.setQcUserId(currentUser.getUserId());
//                //是否进行质检
//                if(qcRecord.getQualifiedQuantity()!=0||qcRecord.getFiedQuantity()!=0){
//                    //保存质检记录
//                    qcRecordService.save(qcRecord);
//                    //修改验收记录为已检
//                    acceptRecordService.updateQcState(qcRecord.getAcceptRecordCode(),2);
//                }
//            }
//            AcceptRecordCriteria accept = new AcceptRecordCriteria();
//            accept.setQcState(0);
//            if(acceptRecordService.findList(accept).size()>0){
//                asnMasterService.updateQcState(criteria.getBillCode(),0);
//            }else {
//                asnMasterService.updateQcState(criteria.getBillCode(),3);
//            }

            List<QcRecord> qcRecordList = criteria.getQcRecordList();
            for (QcRecord qcRecord : qcRecordList) {
                QcResultCriteria qcResultCriteria = new QcResultCriteria();
                qcResultCriteria.setBillCode(qcRecord.getAcceptRecordCode());
                qcResultCriteria.setQcResult(qcRecord.getQcResult());
                //合格数量
                qcResultCriteria.setQualifiedQuantity(qcRecord.getQualifiedQuantity());
                //不合格数量fiedQuantity
                qcResultCriteria.setFiedQuantity(qcRecord.getFiedQuantity());
                //让步数量concessionQuantity
                qcResultCriteria.setConcessionQuantity(qcRecord.getConcessionQuantity());
                //检验时间qcTime
                qcResultCriteria.setQcTime(qcRecord.getQcTime());
                qcRecordService.qcResult(qcResultCriteria, currentUser);
                //回传erp
                AcceptRecord acceptRecord = acceptRecordService.getOneByField("accept_record_code", criteria.getBillCode());
                String billId = acceptRecordService.billToErpNew(acceptRecord.getAsnBillNo(), criteria.getBillCode());
                //erp审核回传
                if(billId != null){
                    acceptRecordService.checkBillToErp(billId);
                }else {
                    try {
                        throw new Exception("质检回传erp报错");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            //全部合格
            AcceptRecordCriteria acceptRecordCriteria = new AcceptRecordCriteria();
            acceptRecordCriteria.setAsnBillNo(criteria.getBillCode());
            List<AcceptRecord> list = acceptRecordService.findList(acceptRecordCriteria);
            for (AcceptRecord acceptRecord : list) {

                QcResultCriteria qcResultCriteria = new QcResultCriteria();
                qcResultCriteria.setBillCode(acceptRecord.getAcceptRecordCode());
                qcResultCriteria.setQcResult(1);
                //合格数量
                qcResultCriteria.setQualifiedQuantity(acceptRecord.getQuantity());
                //不合格数量fiedQuantity
                qcResultCriteria.setFiedQuantity(0.0);
                //让步数量concessionQuantity
                qcResultCriteria.setConcessionQuantity(0.0);
                //检验时间qcTime
                qcResultCriteria.setQcTime(DateUtils.getNowDateTimeString());
                qcRecordService.qcResult(qcResultCriteria, currentUser);
                //回传erp
//                AcceptRecord acceptRecord = acceptRecordService.getOneByField("accept_record_code", criteria.getBillCode());
                String billId = acceptRecordService.billToErpNew(acceptRecord.getAsnBillNo(), criteria.getBillCode());
                //erp审核回传
                if(billId != null){
                    acceptRecordService.checkBillToErp(billId);
                }else {
                    try {
                        throw new Exception("质检回传erp报错");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "归档质检记录 传billNo", notes = "归档质检记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/file")
    public Result file(@RequestBody FileData fileData, @ApiIgnore @User CurrentUser currentUser) {
        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        for(int i=0;i<fileData.getDetailNos().size();i++){
            String detailNo = fileData.getDetailNos().get(i);
            qcRecordService.createFile(detailNo,currentUser);
        }

        return ResultGenerator.genSuccessResult();
    }

}
